package com.sqx.modules.orders.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.annotation.LoginUser;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.response.MyOrderResponse;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.taking.entity.OrderTaking;
import com.sqx.modules.taking.service.OrderTakingService;
import com.sqx.modules.task.dao.HelpTakeDao;
import com.sqx.modules.task.entity.HelpOrder;
import com.sqx.modules.task.entity.HelpTake;
import com.sqx.modules.task.service.HelpTakeService;
import com.sqx.modules.utils.SenInfoCheckUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@RestController
@AllArgsConstructor
@RequestMapping("/app/orders")
@Api(value = "app订单信息", tags = {"app订单信息"})
public class AppOrdersController {

    private OrdersService ordersService;
    private HelpTakeDao helpTakeDao;
    private UserService userService;
    private CommonInfoService commonInfoService;
    private OrderTakingService orderTakingService;
    private HelpTakeService helpTakeService;

    @ApiOperation("下单播报")
    @GetMapping("/orderBroadcast")
    public Result orderBroadcast(){
        return ordersService.orderBroadcast();
    }

    @Login
    @ApiOperation("生成订单")
    @GetMapping("/generateOrder")
    public Result generateOrder(@RequestAttribute Long userId, @ApiParam("接单/会员id") Long id, @ApiParam("订单类型") Long type,
                                @ApiParam("订单数量") Long orderNumber, @ApiParam("备注") String remarks, Long addressId,
                                String startTime, Long serviceTimeId, Long couponId,String khname,String khphone) {
        return ordersService.generateOrder(userId, id, type, orderNumber, remarks, addressId, startTime,
                serviceTimeId, couponId,khname,khphone);
    }

    @Login
    @ApiOperation("修改订单地址")
    @PostMapping("/updateOrdersAddress")
    public Result updateOrdersAddress(Long ordersId, Long addressId) {
        return ordersService.updateOrdersAddress(ordersId, addressId);
    }


    /**
     * 查看我的订单
     */
    @Login
    @ApiOperation("查看我的订单")
    @GetMapping("/selectMyOrder")
    public Result selectMyOrder(@RequestAttribute Long userId, Long page, Long limit, String status, Long orderTakingUserId) {
        Page<MyOrderResponse> iPage = new Page<>(page, limit);
        if("0".equals(status)){
            status=null;
        }else if("-1".equals(status)){
            status="0";
        }
        return ordersService.selectMyOrder(userId, iPage, status, orderTakingUserId);
    }

    /**
     * 生成充值订单
     */
    @Login
    @ApiOperation("生成充值订单")
    @GetMapping("/investOrder")
    public Result investOrder(@RequestAttribute Long userId, @RequestParam Double money, @RequestParam Integer classify) {

        return ordersService.investOrder(userId, money, classify);
    }

    /**
     * 修改订单状态
     */
    @Login
    @ApiOperation("修改订单状态")
    @GetMapping("/cancelOrder")
    public Result cancelOrder(@RequestAttribute Long userId, Long id, String status, String code,
                              String startServiceImg, String endServiceImg, BigDecimal money,
                              String startServiceLongitude, String startServiceLatitude,
                              String endServiceLongitude, String endServiceLatitude) {
        Orders orders = ordersService.getById(id);
        if (userId.equals(orders.getUserId())) {
            code = orders.getCode();
        }
        return ordersService.cancelOrder(id, status, code, startServiceImg, endServiceImg, money, startServiceLongitude,
                startServiceLatitude, endServiceLongitude, endServiceLatitude,1);
    }

    @Login
    @ApiOperation("修改订单预约时间")
    @PostMapping("/updateStartTime")
    public Result updateStartTime(Long ordersId, String startTime, String remarks) {
        Orders orders = ordersService.getById(ordersId);
        orders.setStartTime(startTime);
        orders.setRemarks(remarks);
        ordersService.updateById(orders);
        return Result.success();
    }


    /**
     * 假删除订单
     */
    @Login
    @ApiOperation("假删除订单")
    @GetMapping("/deleteOrder")
    public Result deleteOrder(Long id) {

        return ordersService.deleteOrder(id);
    }

    /**
     * 查看订单详情
     */
    @Login
    @ApiOperation("查看订单详情")
    @GetMapping("/queryOrders")
    public Result queryOrders(Long id) {
        return ordersService.queryOrders(id);
    }


    @Login
    @GetMapping("/selectMyTakeOrders")
    @ApiOperation("查询我的接单")
    public Result selectMyTakeOrders(Integer page, Integer limit, @RequestAttribute Long userId, Integer status, Long staffUserId, String name, String phone, String startTime, String staffUserName, String ordersNo) {
        if(StringUtils.isNotBlank(startTime)){
            String[] split = startTime.split("-");
            //获取年月日
            String month=split[1];
            month=String.valueOf(Integer.parseInt(month));
            String day=split[2];
            day=String.valueOf(Integer.parseInt(day));
            startTime=split[0]+"-"+month+"-"+day;
        }

        return ordersService.selectMyTakeOrders(page, limit, userId, status, staffUserId, name, phone, startTime, staffUserName, ordersNo);
    }


    @Login
    @GetMapping("/selectStaffUserOrders")
    @ApiOperation("查询员工订单")
    public Result selectStaffUserOrders(Integer page, Integer limit, @RequestAttribute Long userId, Integer status, String name, String phone, String startTime, String ordersNo, Long orderTakingUserId) {
        return ordersService.selectStaffUserOrders(page, limit, userId, status, name, phone, startTime, ordersNo, orderTakingUserId);
    }

    @GetMapping("/selectStaffUserOrdersByStaffUserId")
    @ApiOperation("查询员工订单")
    public Result selectStaffUserOrdersByStaffUserId(Integer page, Integer limit, Long staffUserId, Integer status, String name, String phone, String startTime, String ordersNo, Long orderTakingUserId) {
        return ordersService.selectStaffUserOrders(page, limit, staffUserId, status, name, phone, startTime, ordersNo, orderTakingUserId);
    }


    @Login
    @PostMapping("/payMoney")
    @ApiOperation("零钱去支付")
    public Result payMoney(Long ordersId) {
        return ordersService.payMoney(ordersId);
    }


    @Login
    @GetMapping("/getOrdersRemind")
    @ApiOperation("获取服务订单")
    public Result getOrdersRemind(@RequestAttribute Long userId) {
        Integer ordersRemind = ordersService.getOrdersRemind(userId);
        ordersService.updateOrdersIsRemind(userId);
        return Result.success().put("data", ordersRemind);
    }

    @Login
    @GetMapping("/selectTeamOrdersList")
    @ApiOperation("获取团队订单")
    public Result selectTeamOrdersList(@RequestAttribute Long userId, Integer page, Integer limit, Integer type, Integer status) {
        return ordersService.selectTeamOrdersList(page, limit, userId, type, status);
    }

    @Login
    @GetMapping("/selectTeamUserList")
    @ApiOperation("获取团队列表")
    public Result selectTeamUserList(@LoginUser UserEntity user, Integer page, Integer limit, Integer type) {
        return ordersService.selectTeamUserList(page, limit, user.getInvitationCode(), type, user.getUserId());
    }

    @Login
    @GetMapping("/selectTeamStatistics")
    @ApiOperation("团队统计")
    public Result selectTeamStatistics(@LoginUser UserEntity user) {
        Double oneTeamMoney = ordersService.selectOrdersMoneyCountByUserId(user.getUserId(), 1);
        oneTeamMoney+=helpTakeDao.selectHelpTakeMoneyCountByUserId(user.getUserId(),1);

        Integer oneTeamCount = ordersService.selectUserCountByInvitationCode(user.getInvitationCode(), 1);

        Double twoTeamMoney = ordersService.selectOrdersMoneyCountByUserId(user.getUserId(), 2);
        twoTeamMoney+=helpTakeDao.selectHelpTakeMoneyCountByUserId(user.getUserId(),2);

        Integer twoTeamCount = ordersService.selectUserCountByInvitationCode(user.getInvitationCode(), 2);
        Integer teamCount = oneTeamCount + twoTeamCount;
        BigDecimal teamMoney = BigDecimal.valueOf(oneTeamMoney).add(BigDecimal.valueOf(twoTeamMoney));
        Map<String, Object> result = new HashMap<>();
        result.put("teamMoney", teamMoney);
        result.put("teamCount", teamCount);
        result.put("oneTeamMoney", oneTeamMoney);
        result.put("oneTeamCount", oneTeamCount);
        result.put("twoTeamMoney", twoTeamMoney);
        result.put("twoTeamCount", twoTeamCount);
        return Result.success().put("data", result);
    }

    @Login
    @PostMapping("/assignTask")
    @ApiOperation("指派员工")
    @Transactional(rollbackFor = Exception.class)
    public Result assignTask(Long userId, Long ordersId) {
        Orders orders = ordersService.getById(ordersId);
        orders.setStaffUserId(userId);
        ordersService.updateById(orders);

        //消息推送
        UserEntity userEntity = userService.selectUserById(userId);
        String templateId = commonInfoService.findOne(621).getValue();
        if(StringUtils.isNotBlank(userEntity.getOpenId())){
            List<String> msgList=new ArrayList<>();
            msgList.add(orders.getOrdersNo());
            OrderTaking orderTaking = orderTakingService.getById(orders.getOrderTakingId());
            String serviceName = orderTaking.getGameId();
            if(serviceName.length()>15){
                serviceName=serviceName.substring(0,15)+"...";
            }
            msgList.add(serviceName);
            msgList.add(orders.getStartTime());
            msgList.add(orders.getName());
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),templateId,null,msgList,6);
        }
        if(StringUtils.isNotBlank(userEntity.getPhone())){
            userService.sendMsg(userEntity.getPhone(),"assignTask",null);
        }
        return Result.success();
    }

    @Login
    @GetMapping("/selectStaffUserStatistics")
    @ApiOperation("查询员工统计")
    public Result selectStaffUserStatistics(@RequestAttribute Long userId, Long companyId) {
        String format = DateUtils.format(new Date(), "yyyy-MM-dd");
        //今日订单 服务+任务
        int dayCount = ordersService.count(new QueryWrapper<Orders>().eq("staff_user_id", userId).like("start_time", format + "%").in("state", 1, 2, 4));
        dayCount += helpTakeDao.selectCount(new QueryWrapper<HelpTake>().eq("company_id", userId).eq("status", 3).like("start_time", format + "%"));
        //总服务量  服务+任务
        int count = ordersService.count(new QueryWrapper<Orders>().eq("staff_user_id", userId).in("state", 1, 2, 4));
        count += helpTakeDao.selectCount(new QueryWrapper<HelpTake>().eq("company_id", userId).eq("status", 3));
        //排行榜 第几名
        Integer ranKing = ordersService.selectRankingByUserId(userId, companyId);
        Map<String, Object> result = new HashMap<>();
        result.put("dayCount", dayCount);
        result.put("count", count);
        result.put("ranKing", ranKing);
        return Result.success().put("data", result);
    }

    @Login
    @GetMapping("/selectCompanyStatistics")
    @ApiOperation("公司统计")
    public Result selectCompanyStatistics(@RequestAttribute Long userId) {
        //派单统计
        Integer counts = ordersService.selectOrdersCountByCompany(userId);
        //派单金额
        BigDecimal money = ordersService.selectOrdersMoneyByCompany(userId);
        Map<String, Object> result = new HashMap<>();
        result.put("counts", counts);
        result.put("money", money.setScale(2,BigDecimal.ROUND_DOWN));
        return Result.success().put("data", result);
    }

    @Login
    @GetMapping("/selectStaffUserStatisticsByTime")
    @ApiOperation("员工统计")
    public Result selectStaffUserStatisticsByTime(Long userId, String time, Long companyId) {
        String taskTime=null;
        //派单数量
        if(StringUtils.isNotBlank(time)){
            String[] split = time.split("-");
            //获取年月日
            String month=split[1];
            month=String.valueOf(Integer.parseInt(month));
            String day=split[2];
            day=String.valueOf(Integer.parseInt(day));
            taskTime=split[0]+"-"+month+"-"+day;
        }else{
            time=null;
        }

        Map<String, Object> serviceCount = ordersService.selectOrdersCountByStaffUser(userId, companyId,taskTime, time, null);
        //派单金额
        Map<String, Object> serviceMoney = ordersService.selectOrdersMoneyByStaffUser(userId, companyId, taskTime, time, null);
        //派单退款数量
        Map<String, Object> refundCount = ordersService.selectOrdersRefundCountByStaffUser(userId, companyId,taskTime,  time, null);
        //派单退款金额
        Map<String, Object> refundMoney = ordersService.selectOrdersRefundMoneyByStaffUser(userId, companyId,taskTime,  time, null);
        Map<String, Object> result = new HashMap<>();
        result.put("serviceCount", serviceCount);
        result.put("serviceMoney", serviceMoney);
        result.put("refundCount", refundCount);
        result.put("refundMoney", refundMoney);

        return Result.success().put("data", result);
    }

    @Login
    @GetMapping("/selectStaffUserOrdersByTime")
    @ApiOperation("员工服务订单统计排行榜")
    public Result selectStaffUserOrdersByTime(Integer page, Integer limit, @RequestAttribute Long userId, String startTime, String endTime, String phone, String userName) {
        return ordersService.selectStaffUserOrdersByTime(page, limit, userId, startTime, endTime, phone, userName);
    }

    @Login
    @GetMapping("/selectStaffUserHelpTakesByTime")
    @ApiOperation("员工任务订单统计排行榜")
    public Result selectStaffUserHelpTakesByTime(Integer page, Integer limit, @RequestAttribute Long userId, String startTime, String endTime, String phone, String userName) {
        return ordersService.selectStaffUserHelpTakesByTime(page, limit, userId, startTime, endTime, phone, userName);
    }

    @Login
    @GetMapping("/selectStaffStatistics")
    @ApiOperation("员工订单统计")
    public Result selectStaffStatistics(@RequestAttribute("userId") Long userId, String startTime, String endTime) {
        return Result.success().put("data", ordersService.selectStaffStatistics(userId, startTime, endTime));
    }

    @Login
    @GetMapping("/selectNowDayOrders")
    @ApiOperation("接单任务今日订单")
    public Result selectNowDayOrders(Integer page, Integer limit, @RequestAttribute Long userId) {
        return Result.success().put("data", ordersService.selectNowDayOrders(page, limit, userId));
    }

    @Login
    @PostMapping("/repairFee")
    @ApiOperation("补费")
    public Result repairFee(@RequestAttribute Long userId, Long ordersId, BigDecimal money, Integer payType,Integer orderType, HttpServletRequest request) throws Exception {
        return ordersService.repairFee(userId, ordersId, money, payType,orderType,request);
    }

    @Login
    @GetMapping("/getOrderStatusCount")
    @ApiOperation("订单角标")
    public Result getOrderStatusCount(@RequestAttribute Long userId){
        return Result.success().put("data", ordersService.getOrderStatusCount(userId));
    }

    @Login
    @GetMapping("/selectRefundMoney")
    @ApiOperation("获取订单剩余可退金额")
    public Result selectRefundMoney(Long ordersId,Integer orderType){
        return ordersService.selectRefundMoney(ordersId, orderType);
    }

    @Login
    @PostMapping("/refundMoney")
    @ApiOperation("部分退款")
    public Result refundMoney(Long ordersId,BigDecimal money,Integer orderType){
        return ordersService.refundMoney(ordersId, money, orderType);
    }

    @Login
    @PostMapping("/refundOrders")
    @ApiOperation("订单退款")
    public Result refundOrders(Long ordersId,Integer orderType){
        return ordersService.refundOrders(ordersId,orderType);
    }


}
